<?php
/**
 * Created by PhpStorm.
 * User: Celebration-Grey
 * Date: 2017/4/4
 * Time: 15:34
 */

namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Input;

class UserController extends  Controller
{

    public function login(){
        if($_POST){
            $mutipledata = [];
            $mutipledata['email'] = Input::get('user_email');
            $mutipledata['password'] = Input::get('user_password');
            if($this->isEmail($mutipledata['email']) && $this->isPassword($mutipledata['password'])){
                $token = $this->passwordLogin($mutipledata['email'],$mutipledata['password']);
                if($token){
                    return $this->response(200,"登录成功，即将进入新世界！",$token);
                }
                else{
                    return $this->response(304,"账号和密码不匹配，我们无法放你进去！",null);
                }
            }
            else{
                return $this->response(304,"不要输入一些奇怪的东西给我，我看不懂！",null);
            }
        }
        else{
            return $this->response(503,"不要做些奇怪的事情啊喂！如果不是故意的话，刷新页面试试吧！",null);
        }
    }

    public function register(){
        if($_POST){
            if(Input::has("user_nickname")&&Input::has("user_password")&&Input::has("re_password")&&Input::has("php_session_id")&&Input::has("user_email")&&Input::has("code")){
                $mutipledata = [];
                $mutipledata['user_password'] = Input::get("user_password");
                if($this->isPassword($mutipledata['user_password'])){
                    $mutipledata['re_password'] = Input::get("re_password");
                    if($mutipledata['user_password']==$mutipledata['re_password']){
                        $mutipledata['user_nickname'] = Input::get("user_nickname");
                        if($this->isNickName($mutipledata['user_nickname'])){
                            if(!$this->isNicknameExist($mutipledata['user_nickname'])){
                                $mutipledata['code'] = Input::get('code');
                                $mutipledata['php_session_id'] = Input::get('php_session_id');
                                $mutipledata['user_email'] = Input::get('user_email');
                                if($this->verificate($mutipledata['php_session_id'],$mutipledata['code'],$mutipledata['user_email'])){
                                    $user_token = $this->userAdd($mutipledata['user_nickname'],$mutipledata['user_email'],$mutipledata['user_password']);
                                    setcookie('user_token',$user_token,time()+3600*24*7);
                                    $this->response(200,"恭喜您！完成了艰难的注册过程！",null);
                                }else{
                                    $this->response(304,"口令对不上！应该是过期了吧，刷新重来试试吧！",$mutipledata['code']);
                                }
                            }else{
                                $this->response(304,"英雄所见略同！但是大家只会记住一个人！",$mutipledata['user_nickname']);
                            }
                        }
                        else{
                            $this->response(304,"不要用些奇怪的名字啊喂！",$mutipledata['user_nickname']);
                        }
                    }else{
                        $this->response(304,"你为什么会有两个不同的秘密？",null);
                    }
                }else{
                    $this->response(304,"用些奇怪的密码，你自己记得住吗？",null);
                }
            }else{
                $this->response(304,"你少了某样的东西啊喂！",null);
            }
        }else{
            $this->response(503,"不要做些奇怪的事情啊喂！如果不是故意的话，刷新页面试试吧！",null);
        }
    }

    public function email(){
        if(Input::has("email")) {
            $email = Input::get("email");
            if ($this->isEmail($email)) {
                if (!$this->isEmailExist($email)) {
                    $this->sendEmail($email);
                }else{
                    $this->response(304,"邮箱已存在",$email);
                }
            } else {
                $this->response(304,"邮箱格式不正确",$email);
            }
        }
    }

    public function logout(){
        setcookie('user_token','',time()-3600);
    }

    public function cookieLogin(){
        if(isset($_COOKIE['user_token'])){
            $user_token = $_COOKIE['user_token'];
            $info = $this->getSimpleInfoByToken($user_token);
            if($info){
                return $this->response(200,"身边验证成功！",$info);
            }else{
                setcookie('user_token','',time()-3600,'/');
                return $this->response(304,"身边验证失败！",$info);
            }
        }else{
            return $this->response(302,"令牌已过期！",null);
        }
    }

    public function getResetCode(){
        if($_POST){
            if(isset($_COOKIE['php_session_id'])){
                $mutipledata = [];
                $mutipledata['email'] = Input::get('user_email');
                if($this->isEmail($mutipledata['email'])) {
                    if ($this->isEmailExist($mutipledata['email'])) {
                        $mutipledata['code'] = $this->getRand();
                        $flag = $this->sendResetEmail($mutipledata['email'], $mutipledata['code']);
                        if ($flag) {
                            $mutipledata['php_session_id'] = $_COOKIE['php_session_id'];
                            $mutipledata['code'] = hash('md5', $mutipledata['code']);
                            $result = $this->resetAdd($mutipledata);
                            if ($result) {
                                $this->response(200, "邮件发送成功，请注意您的垃圾箱Orz", null);
                            }else{
                                $this->response(304, "未知错误！", $result);
                            }
                        }else {
                            $this->response(304,"邮件发送失败",null);
                        }
                    }else{
                        $this->response(304,"这个邮箱根本不存在!",$mutipledata);
                    }
                }else{
                    $this->response(304,"这真的是邮箱吗？",$mutipledata);
                }
            }else{
                $this->response(304,"页面过期啦！请刷新页面",null);
            }
        }else{
            $this->response(503,"不听不听，王八念经",null);
        }
    }

    public function resetPassword(){
        if($_POST){
            if(isset($_COOKIE['php_session_id'])){
                $data = [];
                $data['email'] = Input::get('user_email');
                $data['password'] = Input::get('user_password');
                $data['repassword'] = Input::get('re_password');
                if($this->isPassword($data['password'])){
                    if($data['password']==$data['repassword']){
                        $data['code'] = hash('md5',Input::get('code'));
                        $data['php_session_id'] = $_COOKIE['php_session_id'];
                        $flag = $this->resetVerify($data);
                        if($flag){
                            $data['password'] = hash('md5',$data['password']);
                            $result = $this->resetUserPassword($data['email'],$data['password']);
                            if ($result){
                                $this->resetDelete($data['email']);
                                $this->response(200,"重置密码成功！恭喜回来！",null);
                            }else{
                                $this->response(304,"未知错误！",$result);
                            }
                        }else{
                            $this->response(304,"验证码有误，或者你变动了某些内容！",null);
                        }
                    }else{
                        $this->response(304,"两次密码不一致啊喂！",$data);
                    }
                }else{
                    $this->response(304,"你是觉得你忘掉的密码不够难吗？",$data);
                }
            }else{
                $this->response(304,"页面过期啦！请刷新页面",null);
            }
        }else{
            $this->response(503,"不听不听，王八念经",null);
        }
    }

    public function infoUpdate(){}


    public function getSession(){
        if(isset($_COOKIE['php_session_id'])){
            $data = [];
            $data['php_session_id'] = $_COOKIE['php_session_id'];
            $this->response(304,"Session have been exitst",$data);
        }else{
            $hash_session_id = $this->getSessionId();
            setcookie('php_session_id', $hash_session_id, time()+1800);
            $data = [];
            $data['php_session_id'] = $hash_session_id;
            $this->response(200,"Session Setting Success",$data);
        }
    }





    private function passwordLogin($email,$password){
        $users = DB::table("weibo_users");
        $hash_password = hash('md5',$password);
        $token = null;
        $result = $users->where('user_email','=',$email)->where('user_password','=',$hash_password)->select('user_id')->get();
        if ($result){
            $token = hash('md5',$this->getRand());
            $users->where('user_id','=',$result[0]->user_id)->update(['user_token' => $token]);
            setcookie('user_token',$token,time()+3600*24*7,'/');
        }else{
            setcookie("user_token", "", time()-3600,'/');
        }
        return $token;
    }

    private function getSessionId(){
        $session_id = $this->getRand();
        $hash_session_id = hash('md5',$session_id);
        $temporary = DB::table('weibo_temporary');
        $result = $temporary->where('temporary_session',$hash_session_id)->count();
        if ($result){
            $this->getSessionId();
        }
        else{
            $temporary->insert(
                ['temporary_session' => $hash_session_id]
            );
            return $hash_session_id;
        }
    }

    private function userAdd($nickname,$email,$password){
        $users = DB::table('weibo_users');
        $hash_password = hash('md5',$password);
        $token = hash('md5',$this->getRand());
        $result = $users->where('user_token','=', $token)->count();
        if($result){
            $this->userAdd($nickname,$email,$password);
        }
        else{
            $users->insert([
                'user_nickname' => $nickname,
                'user_email' => $email,
                'user_password' => $hash_password,
                'user_token' => $token
            ]);
            return $token;
        }
    }

    private function resetAdd($data){
        $reset = DB::table('weibo_reset');
        $result = $reset->insert([
            'reset_email' => $data['email'],
            'reset_code' => $data['code'],
            'reset_session' => $data['php_session_id']
        ]);
        return $result;
    }

    private function resetVerify($data){
        $reset = DB::table('weibo_reset');
        $result = $reset->where('reset_email','=',$data['email'])->where('reset_code','=',$data['code'])->where('reset_session','=',$data['php_session_id'])->count();
        return $result;
    }

    private function resetDelete($email){
        $reset = DB::table('weibo_reset');
        $reset->where('reset_email','=',$email)->delete();
    }

    private function resetUserPassword($email,$newPassword){
        $user = DB::table('weibo_users');
        $result = $user->where('user_email','=',$email)->update(['user_password' => $newPassword]);
        return $result;
    }

    private function getSimpleInfoByToken($token){
        $users = DB::table('weibo_users');
        $result = $users->where('user_token', '=', $token)->select('user_id','user_nickname','user_head_img','user_card_img','user_sex','user_bowen_count','user_followed_count','user_following_count','user_level')->get();
        return $result;
    }

    private function isEmail($email){
        $pattern = "/^[_a-zA-Z0-9\-\.]+@([\-_a-zA-Z0-9]+\.)+[a-zA-Z0-9]{2,3}$/";
        if(preg_match($pattern,$email)){
            return true;
        }
        else{
            return false;
        }
    }

    private function isPassword($password){
        $pattern = "/\w{6,18}$/";
        if(preg_match($pattern,$password)){
            return true;
        }
        else{
            return false;
        }
    }

    private function isNickName($nickname){
        $pattern = "/[@#\$%\^&\*]+/";
        if (preg_match($pattern,$nickname)){
            return false;
        }
        else{
            return true;
        }
    }

    private function isNicknameExist($nickname){
        $users = DB::table('weibo_users');
        $result = $users->where('user_nickname','=',$nickname)->count();
        if($result){
            return true;
        }
        else{
            return false;
        }
    }

    private function isEmailExist($email){
        $users = DB::table('weibo_users');
        $result = $users->where('user_email', '=', $email)->count();
        if($result){
            return true;
        }
        else{
            return false;
        }
    }

    private function verificate($phpsessionid,$code,$email){
        $temporary = DB::table('weibo_temporary');
        $result = $temporary->where('temporary_session','=',$phpsessionid)->where('temporary_code','=',$code)->where('temporary_email','=',$email)->count();
        if($result){
            return true;
        }
        else{
            return false;
        }
    }

    private function sendEmail($email)
    {
        if(isset($_COOKIE['php_session_id'])){
            $session_id = $_COOKIE['php_session_id'];
            $code = $this->getVerificationCode($session_id,$email);
            $flag = Mail::send('emails.verification',['code'=>$code],function($message) use ($email){
                $message ->to($email)->subject('微博注册通知邮件');
            });
            if($flag){
                $data = [];
                $data['php_session_id'] = $session_id;
                $this->response(200,"邮件发送成功",$data);
            }else{
                $this->response(304,"邮件发送失败",$flag);
            }
        } else{
            $this->response(304,"非法请求,请刷新页面",null);
        }
    }

    private function sendResetEmail($email,$code){
        $flag = Mail::send('emails.reset',['code'=>$code],function($message) use ($email){
            $message ->to($email)->subject('微博重置密码通知邮件');
        });
        return $flag;
    }

    private function getVerificationCode($session_id,$email){
        $code = $this->getRand();
        $temporary = DB::table('weibo_temporary');
        $temporary->where('temporary_session', '=', $session_id)->update(
            ['temporary_code' => $code,'temporary_email' => $email]
        );
        return $code;
    }

    private function getRand(){
        $length = 6;
        $min = pow(10 , ($length - 1));
        $max = pow(10, $length) - 1;
        return mt_rand($min,$max);
    }

    private function response($status,$message,$data){
        $response = [];
        $response['status'] = $status;
        $response['message'] = $message;
        $response['data'] = $data;
        return response()->json($response);
    }
}